const connection = require('../app/database');
const Db = require('../utils/db')

class UserService extends Db {
    // 创建用户
    async create(user) {
        try {
            // 获取用户信息
            const { name, password } = user;

            const statement = 'INSERT INTO `user` (name, password) VALUES (?, ?);';

            const [result] = await connection.execute(statement, [name, password]);

            return result;
        } catch (error) {
            console.error('UserService - create:', error);
            throw error; // 抛出异常，让调用者处理
        }
    }

    // 根据用户名查找用户
    async findUserByName(name) {
        try {
            const statement = 'SELECT * FROM `user` WHERE name=?;';

            const [result] = await connection.execute(statement, [name]);

            return result;
        } catch (error) {
            console.error('UserService - findUserByName:', error);
            throw error; // 抛出异常，让调用者处理
        }
    }

    // 根据用户ID查找头像信息
    async findAvatarById(userId) {
        try {
            const statement = 'SELECT * FROM `avatar` WHERE user_id=?;';

            const [result] = await connection.execute(statement, [userId]);
            // console.log('result.pop()=>', result.pop())

            return result.pop(); // 返回结果数组的最后一个元素
        } catch (error) {
            console.error('UserService - findAvatarById:', error);
            throw error; // 抛出异常，让调用者处理
        }
    }

    // 更新用户头像URL
    async updateUserAvatar(avatarUrl, id) {
        try {
            const statement = 'UPDATE user SET avatar_url = ? WHERE id = ?';

            const [result] = await connection.execute(statement, [avatarUrl, id]);

            return result;
        } catch (error) {
            console.error('UserService - updateUserAvatar:', error);
            throw error; // 抛出异常，让调用者处理
        }
    }
}

module.exports = new UserService("user");
